// 两根线
// 同步：组件 commit -> mutations -> state
// 异步： 组件 dispatch -> actions -> commit -> mutations -> state
import { login, getUserInfo, getDetailUserInfo } from '@/api/user'
import { getToken, setToken, removeToken, setTimestamp } from '@/utils/auth'
export default {
  // 开启命名空间
  namespaced: true,
  // 放数据的地方
  state: {
    token: getToken(),
    userInfo: {}
  },
  // 相当于组件中计算属性
  getters: {},
  // 这个是唯一修改state中数据地方
  mutations: {
    // setCount(state) {}
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  // 写异步的ajax的地方
  actions: {
    // store.commit()
    // getData(store){}
    async login({ commit }, userInfo) {
      const res = await login(userInfo)
      commit('setToken', res)
      setTimestamp()
      console.log(res)
    },
    async getUserInfo({ commit }) {
      const res = await getUserInfo()
      const res1 = await getDetailUserInfo(res.userId)
      commit('setUserInfo', { ...res, ...res1 })
      return res.roles.menus
    },
    logout(store) {
      store.commit('removeToken')
      store.commit('removeUserInfo')
    }

  }

}
